package com.bite.common.security.interceptor;

import cn.hutool.core.util.StrUtil;
import com.bite.common.core.constants.Constants;
import com.bite.common.core.constants.HttpConstants;
import com.bite.common.core.utils.ThreadLocalUtil;
import com.bite.common.security.service.TokenService;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
//实现拦截器
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;
    //调用Controller的Handler之前去重写,从哪个地方拿，取决于当前的bean在哪个容器下被管理，我们使用拦截器，肯定是把这个拦截器的bean
    //交给spring的去管理，交给哪个容器上管理，就是从哪里拿，从system下引入拦截器，那么就从system里面拿
    @Value("${jwt.secret}")
    private String secret;
//拦截器和每个微服务都是绑定的，所以放到这里更加合适
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token=getToken(request);//请求头中获取token
        if(StrUtil.isEmpty(token)){
            return  true;
        }
        Claims claims=tokenService.getClaims(token,secret);
        Long userId= tokenService.getUserId(claims);
        String userKey=tokenService.getUserKey(claims);
        ThreadLocalUtil.set(Constants.USER_KEY,userKey);
        ThreadLocalUtil.set(Constants.USER_ID,userId);
        tokenService.extendToken(claims);
        return true;
    }

   private String getToken(HttpServletRequest request){
        String token=request.getHeader(HttpConstants.AUTHENTICATION);
        if(StrUtil.isNotEmpty(token)&&token.startsWith(HttpConstants.PREFIX)){
            token=token.replaceFirst(HttpConstants.PREFIX,"");
        }
        return token;
   }
   //不能只用ThreadLocal不去清除这个userID
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
